package com.intretech.umsin.security.satoken.handler;

import cn.dev33.satoken.exception.IdTokenInvalidException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.intretech.umsin.common.web.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @version V1.0
 * @ClassName: SecurityExceptionHandler
 * @Description: 功能描述 安全认证异常统一返回
 * @author: 李启联
 * @date: 2022-8-10 14:50
 * @Copyright: Copyright (c) 2022
 */

@Slf4j
@RestControllerAdvice
public class SecurityExceptionHandler {
    /**
     * 权限码异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public ApiResult<Void> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
        return ApiResult.failedResponse(String.valueOf(HttpStatus.FORBIDDEN.value()),"没有访问权限，请联系管理员授权");
    }

    /**
     * 角色权限异常
     */
    @ExceptionHandler(NotRoleException.class)
    public ApiResult<Void> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());
        return ApiResult.failedResponse(String.valueOf(HttpStatus.FORBIDDEN.value()),"没有访问权限，请联系管理员授权");
    }

    /**
     * 认证失败
     */
    @ExceptionHandler(NotLoginException.class)
    public ApiResult<Void> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
        return ApiResult.failedResponse(String.valueOf(HttpStatus.UNAUTHORIZED.value()),"认证失败，无法访问系统资源");
    }

    /**
     * 无效认证
     */
    @ExceptionHandler(IdTokenInvalidException.class)
    public ApiResult<Void> handleIdTokenInvalidException(IdTokenInvalidException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',内网认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
        return ApiResult.failedResponse(String.valueOf(HttpStatus.UNAUTHORIZED.value()),"认证失败，无法访问系统资源");
    }
}